﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Furion.Authorization;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Abc.Web.Core;

/// <summary>
/// JWT认证
/// </summary>
public class JwtHandler : AppAuthorizeHandler
{
    // 此处已经自动验证 Jwt token的有效性了，无需手动验证

    // 检查权限，如果方法是异步的就不用 Task.FromResult 包裹，直接使用 async/await 即可
    // return Task.FromResult(CheckAuthorzie(httpContext));
    public override async Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
    {
        return await CheckAuthorzieAsync(httpContext);
    }

    /// <summary>
    /// 检查权限
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    private static async Task<bool> CheckAuthorzieAsync(DefaultHttpContext httpContext)
    {
        var scopeFactory = App.GetService<IServiceScopeFactory>();
        using var scope = scopeFactory.CreateScope();
        var services = scope.ServiceProvider;

        // 获取缓存服务
        var cacheService = App.GetService<ISysCacheService>(services);

        //获取 controllerName 名称
        var controllerName = httpContext.Request.RouteValues["controller"].ToString();

        //获取ACTION 名称
        var actionName = httpContext.Request.RouteValues["action"].ToString();

        var area = httpContext.Request.RouteValues["area"].ToString();

        var userId = httpContext.User.FindFirstValue(ClaimConst.Claim_UserId)?.ToInt32() ?? 0;

        //验证自定义授权
        var isHasAuth = await cacheService.HasAuthorize(controllerName, actionName, userId, menuAreaType: MenuAreaType.API, area: area);
        if (!isHasAuth)
        {
            return false;
        }
        return true;
    }
}